﻿using MediatR;
using SheepCultivation.Common.Domain;
using SheepCultivation.Common.Dto;
using SheepCultivation.Common.Infrastructure.Interface;
using SheepCultivation.Enum;

namespace SheepCultivation.API.AddliCation.DepartmentW
{
    public class DepartmentCreateHandler : IRequestHandler<DepartmentCreateCommon, Result>
    {
        public readonly IBaseRepository<Department> DepartmentRepository;
        public readonly IBaseRepository<Enterprise> EnterpriseRepository;
        public readonly IBaseRepository<EnterPriseTree> EnterPriseTreeRepository;

        public DepartmentCreateHandler(IBaseRepository<Department> departmentRepository, IBaseRepository<Enterprise> enterpriseRepository, IBaseRepository<EnterPriseTree> enterPriseTreeRepository)
        {
            DepartmentRepository = departmentRepository;
            EnterpriseRepository = enterpriseRepository;
            EnterPriseTreeRepository = enterPriseTreeRepository;
        }

        public async Task<Result> Handle(DepartmentCreateCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.error };
            try
            {
                var res = new Department()
                {
                   DepartmentNext = request.DepartmentNext,
                    DepartmentName = request.DepartmentName,
                    DepartmentIsNot = request.DepartmentIsNot,
                    DepartmentTypeId = request.DepartmentTypeId,
                    DepartmentNum = request.DepartmentNum,
                    DepartmentAdd = request.DepartmentAdd
                };
                DepartmentRepository.Add(res);
                var list = EnterPriseTreeRepository.GetAll().FirstOrDefault(x => x.unitName == res.DepartmentNext);
                var EnterPriseTreeTable = new EnterPriseTree()
                {
                    unitName = res.DepartmentName,
                    Pid = list.EnterPriseTreeId
                };
                EnterPriseTreeRepository.Add(EnterPriseTreeTable);
                result.Code = (int)CommonEnumCode.success;
                result.Msg = "部门信息新增";
            }
            catch (Exception ex)
            {
              
                result.Msg = "部门信息新增失败";
            }
            return result;
        }
    }
}
